﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Reflection;

namespace SGCG.Model
{
    public class TextureFactory
    {

        private class ConstantTexture : ITexture
        {
            public Color Color { get; set; }
            public Color GetColorAt(int x, int y)
            {
                return Color;
            }
        }

        private class PhotoTexture : ITexture
        {
            public PhotoTexture(object photoResource)
            {
                var bmp = new WriteableBitmap(photoResource as UIElement, null);
                width = bmp.PixelWidth;
                height = bmp.PixelHeight;
                colors = new Color[width, height];
                int x, y, p, px;
                for (y = 0, p = 0; y < height; ++y)
                    for (x = 0; x < width; ++x, ++p)
                    {
                        px = bmp.Pixels[p];
                        colors[x, y] = new Color()
                        {
                            A = (byte)((px >> 24) & 0xFF),
                            R = (byte)((px >> 16) & 0xFF),
                            G = (byte)((px >> 8) & 0xFF),
                            B = (byte)((px >> 0) & 0xFF)
                        };
                    }
            }

            public Color GetColorAt(int x, int y)
            {
                return colors[(x % width + width) % width, (y % height + height) % height];
            }

            private int width, height;
            private Color[,] colors;
        }

        public static ITexture CreateTexture(FillType fillType, Color fillColor)
        {
            switch (fillType)
            {
                case FillType.Solid:
                    return new ConstantTexture() { Color = fillColor };
                case FillType.Dragon:
                    return photoTextureDragonInstance;
                case FillType.Cesar:
                    return photoTextureCesarInstance;
                default:
                    return null;
            }
        }

        private static PhotoTexture photoTextureCesarInstance = new PhotoTexture(App.Current.Resources["FotoCesar"]);
        private static PhotoTexture photoTextureDragonInstance = new PhotoTexture(App.Current.Resources["FotoDragon"]);

    }
}
